package uk.co.aetherworks.osc_messaging;

/*
 * Ped-ome
 *
 * AppToPed - Receives Messages from Monome Applications
 *
 * Joe Handford aka Knecht 2011
 *
 */ 

// OSC Include Files
import com.illposed.osc.OSCPortOut;
import com.illposed.osc.OSCPortIn;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCMessage;

// Java Net Include Files

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

// aetherworks imports
import uk.co.aetherworks.debug.*;
 
//class AppToPed extends Debuggable implements RegisterListener, AppStatusListener {
public class AppToPed extends Debuggable implements AppStatusListener {

	OSCPortIn receiver;
	AppStatusInterpreter appListener;
	String appPrefix = "/pedome";
	
	// pedListeningPort fixed - might be better to get next free
	public AppToPed(int pedListeningPort, OSCCmdHandler cmdHandler) {
		DEBUG("** Creating AppToPed bound to port: " + pedListeningPort);
		try
        {
            receiver = new OSCPortIn(pedListeningPort);
        }
        catch (Exception e) { System.out.println("Couldn't create pedome from app receiver!"); }

	    appListener = new AppStatusInterpreter(cmdHandler, this);		
		receiver.addListener("/sys/port", appListener);
		receiver.addListener("/sys/info", appListener);
		receiver.addListener("/sys/prefix", appListener);
		receiver.startListening();
	}
	
	public void attachForwarder(PedToMon aForwarder) {
	    appListener.attachForwarder(aForwarder);
	}
	
	public void detachForwarder() {
	    appListener.detachForwarder();
	}

	public void updateListeners() {
		DEBUG("Updating MonToPed's listeners...");
		receiver.addListener(appPrefix + "/grid/led/set", appListener);
//DEBUG
		receiver.addListener("/grid/led/set", appListener);
//DEBUG
	}
	
/*	public void operationFailed(DNSSDService arg0, int arg1) {
		DEBUG("Operation failed: " + arg0 + " [" + arg1 + "]");
	}

	public void serviceRegistered(DNSSDRegistration registration, int flags, java.lang.String serviceName, java.lang.String regType, java.lang.String domain) {
		DEBUG(serviceName + " service registered.");
	}*/

	public void setAppPrefix(String prefix) {
		appPrefix = prefix;
		appListener.setAppPrefix(prefix);
	}
	
	public void setMonPrefix(String prefix) {
		appListener.setMonPrefix(prefix);
	}
	
	public void close() {
		receiver.stopListening();
		receiver.close();
	}
}
